﻿using System;
using System.Collections.Generic;
using Blazing.BusinessObjects.Tagging;
using NHibernate;
using System.BusinessObjects.Transactions;

namespace Blazing.BusinessObjects.Queries
{
    public class QrySearchProductsByTaxonomyTags
    {
        public static IQuery Query(IList<TaxonomyTag> tags)
        {
            string hql = @"select b1 from Product b1 
                           {0}
                           where {1}";

            //works by inner joining taxonomytags on each term to create a filter,
            //plz redo if you have a better solution...
            string tables = "";
            string wherelist = "";
            for (int i = 0; i < tags.Count; i++)
            {
                tables += string.Format(" join b1.TaxonomyTags btt{0} ", i);
                if (wherelist.Length > 0)
                    wherelist += " and";
                wherelist += string.Format(" btt{0}.ID = :tid{0} ", i);
            }

            IQuery qry = UnitOfWork.CurrentSession.CreateQuery(string.Format(hql, tables, wherelist));

            for (int i = 0; i < tags.Count; i++)
            {
                qry.SetParameter("tid" + i, tags[i]);
            }

            qry.SetCacheable(true);
            return qry;
        }
    }
}
